#include "hdc1080.h"
#include "iic.h"

uint8_t HDC1080_setResolution(HDC1080_MeasurementResolution humidity, HDC1080_MeasurementResolution temperature) {
	HDC1080_Registers reg;
	reg.HumidityMeasurementResolution = 0;
	reg.TemperatureMeasurementResolution = 0;

	if (temperature == HDC1080_RESOLUTION_11BIT)
		reg.TemperatureMeasurementResolution = 0x01;

	switch (humidity)
	{
		case HDC1080_RESOLUTION_8BIT:
			reg.HumidityMeasurementResolution = 0x02;
			break;
		case HDC1080_RESOLUTION_11BIT:
			reg.HumidityMeasurementResolution = 0x01;
			break;
		default:
			break;
	}
    // NRF_LOG_INFO("reg.rawData: 0x%02x", reg.rawData);
    uint8_t cmd[2] = {0};
    cmd[0]=reg.rawData;
    delay_ms(5);
    // cmd[0]=0x05;
	return I2C_Write_Bytes(HDC1080_ADDR,HDC1080_CONFIGURATION,cmd,2);
}

uint16_t HDC1080_ReadReg(uint8_t addr){

   uint8_t res =0;
   uint8_t cmd[2];
   I2C_Start();                        //起始信号
   res = I2C_SendByte(HDC1080_ADDR << 1, 1);   //发送设备地址+写信号 检测ACK信号
   res = I2C_SendByte(addr, 1);
   delay_ms(20);
   I2C_Start();
   res = I2C_SendByte((HDC1080_ADDR << 1) | 0x01, 1);   //发送设备地址+写信号 检测ACK信号

   cmd[0] = I2C_RecvByte(0);
   cmd[1] = I2C_RecvByte(1);
   I2C_Stop();
   return (cmd[0]*(1<<8) + cmd[1]);


}

uint8_t HDC1080_GetValue_SingleShotWithoutCS(struct TH_Value *value){
	uint8_t res =0;
    uint8_t cmd[2] = {0};
    // res =  I2C_Read_Bytes(HDC1080_ADDR,HDC1080_TEMPERATURE,cmd,2,I2C_MASTER_LAST_NACK);
    // uint16_t conv_tmp = (cmd[0] << 8) | cmd[1];
	 uint16_t conv_tmp = HDC1080_ReadReg(HDC1080_TEMPERATURE);
	 delay_ms(5);
       conv_tmp = HDC1080_ReadReg(HDC1080_TEMPERATURE);
	 delay_ms(10);
    value->CEL = -400 + (short) (((uint32_t) 1650 * conv_tmp) / 65535);
    // I2C_Read_Bytes(HDC1080_ADDR,HDC1080_HUMIDITY,cmd,2,I2C_MASTER_LAST_NACK);
    // conv_tmp = (cmd[0] << 8) | cmd[1];
	conv_tmp = HDC1080_ReadReg(HDC1080_HUMIDITY);
    value->RH = (short) (((uint32_t) 1000 * conv_tmp) / 65535);
    if (value->RH >= 1000)
    {
        value->RH = 999;
    }
    if (value->CEL >= 1000)
    {
        value->CEL = 999;
    }

	return res;
}

